import { Component, Input, Output, EventEmitter, OnInit, forwardRef, OnChanges, SimpleChanges } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { DictService } from '@shared/service/dict.service';

@Component({
  selector: 'app-tree-select',
  template: `
    <nz-tree-select
      style="width: 100%;"
      [nzNodes]="dictList"
      [name]="name"
      nzShowSearch
      nzPlaceHolder="请选择"
      [(ngModel)]="model"
      (ngModelChange)="modelChange($event)"
    >
    </nz-tree-select>
    `,
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => TreeSelectComponent),
    multi: true
  }],
  styleUrls: ['./index.less']
})
export class TreeSelectComponent implements OnInit, ControlValueAccessor, OnChanges {
  model: any;
  @Input() name;
  @Input() url;
  @Input() dictCode: string;
  @Input() dynamicDict = false;
  @Input() nzMode='default';
  @Input() disabled=false;
  expandKeys = [];

  @Output() ngModelChange = new EventEmitter();
  dictList:any[]=[];
  public onModelChange: any = () => { };
  public onModelTouched: any = () => { };
  writeValue(value: any) {
    this.model = value;
  }
  registerOnChange(fn: any): void {
    this.onModelChange = fn;
  }
  registerOnTouched(fn: any): void {
    this.onModelTouched = fn;
  }

  modelChange(value) {
    this.model = value;
    this.onModelChange(this.model); // 主要是要调用这个去重置绑定的model的值
    this.ngModelChange.emit(value);
  }

  constructor(public http: _HttpClient) { }
  ngOnInit(): void {
    this.getDict();
  }
  ngOnChanges(changes: SimpleChanges) {

  }
  getDict() {
    this.http.get(this.url).subscribe((res:any)=>{
      this.dictList=res.result.treeList
      this.expandKeys=res.result.ids
    })
  }
}
